package keter.framework.web.security.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keter.framework.web.util.RequestUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class KeterCryptoAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
	/**
	* Logger for this class
	*/
	private static final Logger logger = LoggerFactory.getLogger(KeterCryptoAuthenticationFilter.class);
            
    /**
     * <p>用于前台加密
     * 
     * @see org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     * @author  gulixing@msn.com
     * @date    2016年7月2日
     */
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException {
    	return super.attemptAuthentication(request, response);
//        if (!request.getMethod().equals("POST")) {
//            throw new AuthenticationServiceException(
//                    "Authentication method not supported: " + request.getMethod());
//        }
//
//        JSONObject json = parseJson(request);
//        String username = (String)json.get(SPRING_SECURITY_FORM_USERNAME_KEY);
//        String password = (String)json.get(SPRING_SECURITY_FORM_PASSWORD_KEY);
//
//        if (username == null) {
//            username = "";
//        }
//
//        if (password == null) {
//            password = "";
//        }
//
//        username = username.trim();
//
//        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
//                username, password);
//
//        // Allow subclasses to set the "details" property
//        setDetails(request, authRequest);
//
//        return this.getAuthenticationManager().authenticate(authRequest);
    }

    private JSONObject parseJson(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        try {
            json = (JSONObject) JSON.parse(RequestUtil.getJson(request));
        } catch (Exception e) {
            //该filter产生的异常不会被KeterExceptionResolver拦截
            logger.error("json解析失败");
        }
        return json;
    }    
    
   
}
